# encoding:utf8
import os
import sys
import shutil
import logging
import subprocess


# old format
'''
CMD_STR = {
	"win32":"ffmpeg -r 44100 -y -i %s %s.mp3",
	"ios":"afconvert -d aac -f 'caff' -c 1 %s %s.caf",
	"android":"ffmpeg -y -i %s -acodec libvorbis %s.ogg"
}

def formatAudio(path , platname):
	logging.info("Formating audio file from [%s] to platname [%s] needed"%(path , platname))
	platdir = os.path.join(path , platname)
	if os.path.isdir(platdir):
		shutil.rmtree(platdir)
	os.mkdir(platdir)
	for filename in os.listdir(path):
		fileobj = os.path.join(path , filename)
		if os.path.splitext(filename)[1] == '.wav' or os.path.splitext(filename)[1] == '.mp3':
			logging.error("@!No format tool ffmpeg and afconvert")

			os.system(CMD_STR[platname] % (fileobj , os.path.join(platdir , os.path.splitext(filename)[0])))
	logging.info("Formating finish!")
'''


class AudioFmt():
    def __init__(self, bin):
        if bin.find("sox") == -1:
            logging.error("Need <sox executable> support!")
            sys.exit()
            return
        self._bin = bin

    def format(self, basefile, tarfile):
        str_cmd = "{BIN} %s %s".replace(
            "{BIN}", self._bin) % (basefile, tarfile)
        logging.info("Format the file <%s> to <%s>" % (basefile, tarfile))

        # caf not support
        if tarfile.find(".caf") != -1:
            if not sys.platform == "darwin":
                logging.error(".caf format need MacOS + afconvert support!")
                return
            else:
                str_cmd = "afconvert -d aac -f 'caff' -c 1 %s %s.caf" % (
                    tarfile, basefile)

        return_code = subprocess.call(str_cmd, shell=True)

        if return_code != 0:
            logging.error(return_code)
            return


if __name__ == "__main__":
    fmter = AudioFmt("D:\\sox-14-4-2\\sox.exe")
    fmter.format("C:\\Users\\wenbin\\Desktop\\test_sox\\gamestart.mp3",
                 "C:\\Users\\wenbin\\Desktop\\test_sox\\gamestart.ogg")
